<?php

namespace App\Admin\Forms;

use App\Admin\Repositories\ProjectAgreement;

use App\Jobs\JobQueue;
use App\Models\User;
use App\Notifications\AuditNotify;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Log;

class AuditPayStatusActionForm extends Form
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $row = $this->payload['row'] ?? null;
        // dd($row);
        $flowMap = ProjectAgreement::getFlowMap();


        $lastLog = $row['audit_log'] ? json_decode($row['audit_log'], true) : [];

        $log = [
            [
                // 'audit_fee' => $input['pay_status'],
                'audit_global_status' => $row['audit_global_status'],
                'audit_user' => Admin::user()->name,
                'audit_time' => date('Y-m-d H:i:s'),
                'pay_status' => isset($input['pay_status']) && !empty($input['pay_status']) ? $input['pay_status'] : '',
                'audit_remark' => $input['audit_remark'] ?? ''
            ],
        ];
        if ($input['pay_status'] == 1) {
            $pay_status = ['pay_status' => $input['pay_status']];
        } else {
            $pay_status = ['pay_status' => $input['pay_status']];
        }

        \App\Models\ProjectAgreement::where('id', $row['id'])
            ->update(array_merge([
                // 'audit_fee' => $input['pay_status'],
                'audit_remark' => ($input['pay_status'] == 1 ? '' : $input['audit_remark']),
                'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
            ], $pay_status));


        return $this
            ->response()
            ->success('操作成功')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('pay_status', '审核状态')
            ->options([1 => '允许支付', -1 => '驳回'])
            ->required()
            ->when(-1, function (Form $form) {
                $form->textarea('audit_remark')->rules('required_if:audit_status,-1', ['required_if' => '请填写完整该项']);
            });
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function
    default()
    {
        return [
            'name'  => 'John Doe',
            'email' => 'John.Doe@gmail.com',
        ];
    }
}
